import { readFile, updateResFile } from '../util/file'
const dataLocation = `${__dirname}/../data/catalogues.json`
import { findTargetNode, deleteTargetNode, changeNodeParent } from '../util/tree'

// 获取所有目录
export const getCatalogues = async () => {
  return await readFile(dataLocation)
}

// 添加目录
export const addCatalogue = async ({newCatalogue}) => {
  try {
    let tree = await getCatalogues()
    newCatalogue.mainId = tree.maxId + 1
    newCatalogue.children = []
    const target = findTargetNode({mainId: newCatalogue.parent, tree})
    if (!target) {
      return {
        data: false,
        message: '父节点不存在！'
      }
    }
    if (!newCatalogue.label.trim()) {
      return {
        data: false,
        message: '节点名称不能为空！'
      }
    }
    target.children.push(newCatalogue)
    tree.maxId += 1
    return await updateResFile(dataLocation, tree)
  } catch (err) {
    return {
      data: false,
      message: err
    }
  }
}

// 重命名文件夹
export const renameCatalogue = async ({mainId, label}) => {
  let tree = await getCatalogues()
  const target = findTargetNode({mainId, tree})
  if (!target) {
    return {
      data: false,
      message: '父节点不存在！'
    }
  }
  if (!label.trim()) {
    return {
      data: false,
      message: '请输入名称！'
    }
  }
  if (target.type === 2) {
    target.label = `${label}.html`
  } else {
    target.label = label
  }
  return await updateResFile(dataLocation, tree)
}

// 移动目录
export const moveCatalogue = async ({mainId, newParent}) => {
  let tree = await getCatalogues()
  const target = findTargetNode({mainId, tree})
  const newParentNode = findTargetNode({mainId: newParent, tree})
  if (!target) {
    return {
      data: false,
      message: '被移动节点不存在！'
    }
  }
  if (!newParentNode) {
    return {
      data: false,
      message: '要移动到的目标节点不存在！'
    }
  }
  // 在老节点中删除该节点
  changeNodeParent({target, tree, newParentNode})
  // 如果删除的是文件，则一并删除相关的兄弟节点（例：删除html文件的同时删除css文件）
  if (target.type === 2 && target.bro) {
    const borTarget = findTargetNode({mainId: target.bro, tree})
    changeNodeParent({target: borTarget, tree, newParentNode})
  }
  return await updateResFile(dataLocation, tree)
}

export default {
  getCatalogues,
  addCatalogue,
  renameCatalogue,
  moveCatalogue
}
